<script setup lang="tsx">
defineOptions({
  name: "GAS_OPERATION_DETECTORMANAGE_ISOLATE"
});

import { ref, h, onUnmounted, markRaw, onActivated } from "vue";
import { useRouter } from "vue-router";
import { queryDetectorIsolateList, revokeTaskDetectorIsolate } from "@/api/modules/operation";
import commonTable from "@/views/common/components/commonTable/index.vue";
import commonSearch from "@/views/common/components/commonSearch/index.vue";
import { View, ValidationHistory, Flag, Bell, Rollback } from "@px-ui/icons-vue";
import { PxMessage, PxMessageBox, PxScrollbar } from "px-ui";
import { useTableCloumns, useSearchOption } from "./hooks";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";

const router = useRouter();

const isImmediate = ref<boolean>(true);
const searchLoading = ref<boolean>(false);
const gap = 88;
const defaultHeight = 606;
const objectModelTableRef = ref<HTMLElement | null>(null);
const commonTableRef = ref<CommonTable.TableRefType>(null);
const commonSearchRef = ref<CommonSearch.SearchFormRefType>(null);
const scrollbarHeight = ref<number>(defaultHeight);
const searchOption = ref<Array<CommonSearch.SearchOption>>(useSearchOption());

const params = ref<any>({});

const operationOptions: Array<CommonTable.operationOptionItemType> = [
  {
    content: "查看",
    auth: "GAS_OPERATION_DETECTORMANAGE_ISOLATE_CHECK_BTN",
    icon: markRaw(View),
    click: (scope: any) => check(scope)
  },
  {
    content: "执行",
    auth: "GAS_OPERATION_DETECTORMANAGE_ISOLATE_EXECUTE_BTN",
    isHidden({ row }: any) {
      //  待执行：1，4   待确认：2，5   待解隔离通知：3   已完成：6   撤回：7
      const { executorIdList = [], taskStatus = 0 } = row;
      if (!executorIdList?.length || !taskStatus) return true;
      const userInfo = localStorage.getItem("userInfo");
      const { userId = null } = JSON.parse(userInfo);
      if (!userId) return true;
      return !executorIdList?.includes(userId) || ![1, 4].includes(taskStatus) || [7].includes(taskStatus);
    },
    icon: markRaw(ValidationHistory),
    click: (scope: any) => execute(scope)
  },
  {
    content: "确认",
    auth: "GAS_OPERATION_DETECTORMANAGE_ISOLATE_CONFIRM_BTN",
    isHidden({ row }: any) {
      //  待执行：1，4   待确认：2，5   待解隔离通知：3   已完成：6   撤回：7
      const { confirmorIdList = [], taskStatus = 0 } = row;
      if (!confirmorIdList?.length || !taskStatus) return true;
      const userInfo = localStorage.getItem("userInfo");
      const { userId = null } = JSON.parse(userInfo);
      if (!userId) return true;
      return !confirmorIdList?.includes(userId) || ![2, 5].includes(taskStatus) || [7].includes(taskStatus);
    },
    icon: markRaw(Flag),
    click: (scope: any) => confirm(scope)
  },
  {
    content: "解隔离通知",
    auth: "GAS_OPERATION_DETECTORMANAGE_ISOLATE_NOTICE_BTN",
    isHidden({ row }: any) {
      //  待执行：1，4   待确认：2，5   待解隔离通知：3   已完成：6   撤回：7
      const { confirmorIdList = [], taskStatus = 0 } = row;
      if (!confirmorIdList?.length || !taskStatus) return true;
      const userInfo = localStorage.getItem("userInfo");
      const { userId = null } = JSON.parse(userInfo);
      if (!userId) return true;
      return !confirmorIdList?.includes(userId) || ![3].includes(taskStatus) || [7].includes(taskStatus);
    },
    icon: markRaw(Bell),
    click: (scope: any) => notice(scope)
  },
  {
    content: "撤回",
    auth: "GAS_OPERATION_DETECTORMANAGE_REVOKE_BTN",
    isHidden({ row }: any) {
      //  待执行：1，4   待确认：2，5   待解隔离通知：3   已完成：6   撤回：7
      const { revokeIdList = [], taskStatus = 0 } = row;
      if (!revokeIdList?.length || taskStatus !== 1) return true;
      const userInfo = localStorage.getItem("userInfo");
      const { userId = null } = JSON.parse(userInfo);
      if (!userId) return true;
      return !revokeIdList?.includes(userId) || ![1].includes(taskStatus) || [7].includes(taskStatus);
    },
    icon: markRaw(Rollback),
    click: (scope: any) => revoke(scope)
  }
];

let defaultParams: any = {};
let currentParams: any = {};

const getRowKey = row => {
  return row.id;
};

const headerCellStyleFn = ({ row, column, rowIndex, columnIndex }: CommonTable.CellType): Record<string, string> => {
  const style = {};
  if (columnIndex === 4) {
    style["text-align"] = "center";
  }
  return style;
};

const updateParams = () => {
  params.value = { ...defaultParams, ...currentParams };
};

const submitSearchFormHandler = (form: any) => {
  currentParams = { ...currentParams, ...form };
  updateParams();
};

const resetSearchFormHandler = () => {
  currentParams = {};
  updateParams();
};

const add = () => {
  const path = "/gas/operation/detectorManage/isolate/add";
  router.push({ path });
};

const check = scope => {
  const {
    row: { id = "", taskStatus: status }
  } = scope;
  if (!id) return;
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  const type = "check";
  router.push({ path: "/gas/operation/detectorManage/isolate/check", query: { type, status, id } });
};

const execute = scope => {
  const {
    row: { id = "", taskStatus: status }
  } = scope;
  if (!id) return;
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  const type = "edit";
  // 执行 1      确认 2     解隔离通知 3
  const c = "1";
  router.push({ path: "/gas/operation/detectorManage/isolate/edit", query: { type, status, id, c } });
};

const confirm = scope => {
  const {
    row: { id = "", taskStatus: status }
  } = scope;
  if (!id) return;
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  const type = "edit";
  // 执行 1      确认 2     解隔离通知 3
  const c = "2";
  router.push({ path: "/gas/operation/detectorManage/isolate/edit", query: { type, status, id, c } });
};

const notice = scope => {
  const {
    row: { id = "", taskStatus: status }
  } = scope;
  if (!id) return;
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  const type = "edit";
  // 执行 1      确认 2     解隔离通知 3
  const c = "3";
  router.push({ path: "/gas/operation/detectorManage/isolate/edit", query: { type, status, id, c } });
};

const revoke = async scope => {
  const {
    row: { id = "", taskStatus: status, detectorCodes = "" }
  } = scope;
  if (!id) return;
  PxMessageBox({
    title: "注意",
    showCancelButton: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        instance.confirmButtonLoading = true;
        instance.confirmButtonText = "撤回中...";
        await revokeTaskDetectorIsolate({ id }, () => {
          instance.confirmButtonLoading = false;
        });
        instance.confirmButtonLoading = false;
        done();
      } else {
        done();
      }
    },
    customStyle: {
      maxWidth: "700px"
    },
    message: h(PxScrollbar, { wrapStyle: { width: "100%", maxHeight: "300px" } }, [
      h(
        "div",
        { style: { paddingRight: "10px", width: "100%", fontSize: "15px", fontWeight: 600, lineHeight: 2.5 } },
        "确定要撤回以下侦测器的隔离工单吗？"
      ),
      h(
        "div",
        { style: { paddingRight: "10px", width: "100%", lineHeight: 1.5, color: "#555", wordBreak: "break-all", wordWrap: "break-word" } },
        detectorCodes.replace(/,/g, "， ")
      )
    ])
  }).then(async () => {
    await commonTableRef.value.queryTableData(null, true);
    PxMessage.success("撤回成功！");
  });
};

const tableCloumns = ref<Array<CommonTable.TableCloumnsType>>(useTableCloumns(check));

onActivated(async () => {
  if (isImmediate.value) {
    await useUpdateDomHeight(scrollbarHeight, objectModelTableRef, gap, defaultHeight);
    isImmediate.value = false;
  } else {
    commonTableRef.value.queryTableData(null, true);
  }
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>

<template>
  <div v-loading="searchLoading" class="detector-isolate">
    <div class="detector-isolate-search">
      <commonSearch
        v-if="searchOption?.length"
        ref="commonSearchRef"
        v-model:loading="searchLoading"
        :row-num="4"
        :operation-span="3"
        :option="searchOption"
        @submit="submitSearchFormHandler"
        @reset="resetSearchFormHandler"
      />
    </div>
    <div class="detector-isolate-btns">
      <px-button v-has="'GAS_OPERATION_DETECTORMANAGE_ISOLATE_ADD_BTN'" type="primary" @click="add">创建工单</px-button>
    </div>
    <div ref="objectModelTableRef" class="detector-isolate-table">
      <commonTable
        ref="commonTableRef"
        indexNeed
        :tooltip-options="{
          placement: 'right'
        }"
        :operationOptions="operationOptions"
        :operationWidth="150"
        :tableCloumns="tableCloumns"
        :height="scrollbarHeight"
        :row-key="getRowKey"
        :header-cell-style="headerCellStyleFn"
        :axiosApi="queryDetectorIsolateList"
        :params="params"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.detector-isolate {
  box-sizing: border-box;
  width: 100%;
  padding: 16px;
  background-color: #fff;

  .detector-isolate-search {
    width: 100%;
  }

  .detector-isolate-btns {
    display: flex;
    align-items: center;
    margin-top: 16px;
  }

  .detector-isolate-table {
    margin-top: 16px;
  }
}
</style>
